package com.cinsea.ext.cjspx;

import com.alibaba.fastjson.JSON;
import com.cinsea.common.Env;
import com.cinsea.common.ExtAction;
import com.cinsea.common.JdbcDao;
import com.cinsea.hrm.service.OrgService;
import com.cinsea.util.NumberUtil;
import com.cinsea.util.StringUtil;
import org.springframework.dao.DataAccessException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;


public class BudgetAction extends ExtAction {
    @Override
    public void execute(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {//todo:草稿状态分摊流程不计入已用预算
        String action = StringUtil.null2String(request.getParameter("action"));
        JdbcDao jdbcDao = Env.getBean("jdbcDao");
        OrgService orgService = Env.getBean("orgService");
        if (action.equalsIgnoreCase("checkcanuse")) {
            String processid = StringUtil.null2String(request.getParameter("processid"));
            String deptid = StringUtil.null2String(request.getParameter("deptid"));
            String kemu2 = StringUtil.null2String(request.getParameter("kemu2"));
            String feedate = StringUtil.null2String(request.getParameter("feedate"));
            float fee = NumberUtil.string2Float(String.valueOf(request.getParameter("fee")), 0);
            String budgetsql = "select cash,startdate,enddate from ut_budgetform where deleted=0 and usedept = ? and twokm=? and startdate<=? and enddate>=?";

            float budgetvalue = 0;
            float usedvalue = 0;

            List<Map> budgetlist = jdbcDao.queryForList(budgetsql, new Object[]{deptid, kemu2, feedate, feedate});
            if (budgetlist.size() > 0) {
                Map budgetmap = budgetlist.get(0);
                budgetvalue = NumberUtil.string2Float(String.valueOf(budgetmap.get("cash")), 0);
                String startdate = (String) budgetmap.get("startdate");
                String enddate = (String) budgetmap.get("enddate");
                if (StringUtil.isEmpty(processid)) {
                    String usedsql = "select isnull(sum(cash),0) from ut_feesallocation where deleted=0 and ftdept=? and subjecttwo=? and createdatetime>=? and createdatetime<=?";
                    usedvalue = (Float) jdbcDao.getJdbcTemplate().queryForObject(usedsql, new Object[]{deptid, kemu2, startdate, enddate}, Float.class);

                } else {
                    String usedsql = "select isnull(sum(cash),0) from ut_feesallocation where deleted=0 and ftdept=? and subjecttwo=? and createdatetime>=? and createdatetime<=? and processid!=?";
                    usedvalue = (Float) jdbcDao.getJdbcTemplate().queryForObject(usedsql, new Object[]{deptid, kemu2, startdate, enddate, processid}, Float.class);
                }
                if (budgetvalue > 0 && fee > (budgetvalue - usedvalue)) {

                    response.getWriter().print(budgetvalue - usedvalue);
                } else {
                    response.getWriter().print("success");
                }
            } else {//未编制预算
                response.getWriter().print("success");
            }
            return;
        }
        if (action.equalsIgnoreCase("getbudgetinfo")) {
            //差旅费:'48f5f3ea39af67b60139af6a43470009' 业务招待费:'48f5f3ea39af67b60139af6a6c70000a'
            String processid = StringUtil.null2String(request.getParameter("processid"));
            String datas = StringUtil.null2String(request.getParameter("datas"));
            String feedate = StringUtil.null2String(request.getParameter("feedate"));
            String totalbudgetsql = "select isnull(sum(cash),0) as cash from ut_budgetform where deleted=0 and usedept = ?  and startdate<=? and enddate>=?";
            String kemubudgetsql = "select cash from ut_budgetform where deleted=0 and usedept = ? and twokm=? and startdate<=? and enddate>=?";
            String usedsql="SELECT isnull(sum(cash),0) FROM ut_feesallocation WHERE deleted=0 and bxrq is not null AND ftdept=?  AND bxrq>=? AND bxrq<=? ";
            String kemuusedsql="SELECT isnull(sum(cash),0) FROM ut_feesallocation WHERE deleted=0 and bxrq is not null AND ftdept=? AND subjecttwo=? AND bxrq>=? AND bxrq<=? ";

            String periodsql = "select startdate,enddate from ut_budgetform where deleted=0 and usedept = ?  and startdate<=? and enddate>=?";
            List<Map> datalist=(List<Map>)JSON.parse(datas);
            String result="";
            for(Map data:datalist){
                String deptid=(String)data.get("dept");
                String hastrip=StringUtil.null2String(data.get("hastrip"));
                String hastreat=StringUtil.null2String(data.get("hastreat"));
                List<Map> periodlist = jdbcDao.queryForList(periodsql, new Object[]{deptid, feedate, feedate});
                if(periodlist.size()==0) {
                    result += orgService.get(deptid).getObjname() + "未编制预算</br></br>";
                    continue;
                }else {
                    Map period = periodlist.get(0);
                    String startdate = (String) period.get("startdate");//预算年度起始日
                    String enddate = (String) period.get("enddate");//预算年度结束日

                    if(hastreat.equals("1")){
                        float kemubudgetvalue = 0; //科目年度预算
                        float kemubudgetvalue_m = 0;//科目月度预算
                        float kemuusedvalue = 0; //科目年度使用值
                        float kemuusedvalue_m = 0;//科目当月使用值
                        try {
                            kemubudgetvalue=(Float) jdbcDao.getJdbcTemplate().queryForObject(kemubudgetsql, new Object[]{deptid,"48f5f3ea39af67b60139af6a6c70000a",feedate, feedate}, Float.class);
                        } catch (Exception e) {
                            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                        }
                        kemubudgetvalue_m=kemubudgetvalue/12;
                        try {
                            kemuusedvalue=(Float) jdbcDao.getJdbcTemplate().queryForObject(kemuusedsql, new Object[]{deptid,"48f5f3ea39af67b60139af6a6c70000a",startdate, enddate}, Float.class);
                        } catch (Exception e) {
                            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                        }
                        try {
                            kemuusedvalue_m=(Float) jdbcDao.getJdbcTemplate().queryForObject(kemuusedsql, new Object[]{deptid,"48f5f3ea39af67b60139af6a6c70000a",getPeriodStart(feedate), getPeriodEnd(feedate)}, Float.class);
                        } catch (Exception e) {
                            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                        }
                        float diff_m=kemubudgetvalue_m-kemuusedvalue_m;
                        if(diff_m>=0){
                            result+=orgService.get(deptid).getObjname() +"本月业务招待费尚有结余:"+new DecimalFormat("#.00").format(diff_m)+"元</br>";
                        }else{
                            result+=orgService.get(deptid).getObjname() +"本月业务招待费已超支:"+new DecimalFormat("#.00").format((-1*diff_m))+"元</br>";
                        }
                        float diff = kemubudgetvalue - kemuusedvalue;
                        if (diff >= 0) {
                            result += orgService.get(deptid).getObjname() + "本年累计业务招待费尚有结余:" + new DecimalFormat("#.00").format(diff) + "元</br>";
                        } else {
                            result += orgService.get(deptid).getObjname() + "本年累计业务招待费已超支:" + new DecimalFormat("#.00").format((-1 * diff)) + "元</br>";
                        }
                    }

                    if (hastrip.equals("1")) {
                        float kemubudgetvalue = 0; //科目年度预算
                        float kemubudgetvalue_m = 0;//科目月度预算
                        float kemuusedvalue = 0; //科目年度使用值
                        float kemuusedvalue_m = 0;//科目当月使用值
                        try {
                            kemubudgetvalue = (Float) jdbcDao.getJdbcTemplate().queryForObject(kemubudgetsql, new Object[]{deptid, "48f5f3ea39af67b60139af6a43470009", feedate, feedate}, Float.class);
                        } catch (Exception e) {
                            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                        }
                        kemubudgetvalue_m = kemubudgetvalue / 12;
                        try {
                            kemuusedvalue = (Float) jdbcDao.getJdbcTemplate().queryForObject(kemuusedsql, new Object[]{deptid, "48f5f3ea39af67b60139af6a43470009", startdate, enddate}, Float.class);
                        } catch (Exception e) {
                            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                        }
                        try {
                            kemuusedvalue_m = (Float) jdbcDao.getJdbcTemplate().queryForObject(kemuusedsql, new Object[]{deptid, "48f5f3ea39af67b60139af6a43470009", getPeriodStart(feedate), getPeriodEnd(feedate)}, Float.class);
                        } catch (Exception e) {
                            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                        }
                        float diff_m = kemubudgetvalue_m - kemuusedvalue_m;
                        if (diff_m >= 0) {
                            result += orgService.get(deptid).getObjname() + "本月差旅费尚有结余:" + new DecimalFormat("#.00").format(diff_m) + "元</br>";
                        } else {
                            result += orgService.get(deptid).getObjname() + "本月差旅费已超支:" + new DecimalFormat("#.00").format((-1 * diff_m)) + "元</br>";
                        }
                        float diff = kemubudgetvalue - kemuusedvalue;
                        if (diff >= 0) {
                            result += orgService.get(deptid).getObjname() + "本年累计差旅费尚有结余:" + new DecimalFormat("#.00").format(diff) + "元</br>";
                        } else {
                            result += orgService.get(deptid).getObjname() + "本年累计差旅费已超支:" + new DecimalFormat("#.00").format((-1 * diff)) + "元</br>";
                        }
                    }
                    float totalbudgetvalue = 0;//月度预算
                    float totalusedvalue = 0;//月度使用值
                    try {
                        totalbudgetvalue=(Float) jdbcDao.getJdbcTemplate().queryForObject(totalbudgetsql, new Object[]{deptid,startdate, enddate}, Float.class)/12;
                    } catch (Exception e) {
                        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                    }
                    try {
                        totalusedvalue=(Float) jdbcDao.getJdbcTemplate().queryForObject(usedsql, new Object[]{deptid,getPeriodStart(feedate), getPeriodEnd(feedate)}, Float.class);
                    } catch (Exception e) {
                        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                    }
                    float diff=totalbudgetvalue-totalusedvalue;
                    if (diff >= 0) {
                        result += "</br>截至目前," + orgService.get(deptid).getObjname() + "累计费用尚有结余:" + new DecimalFormat("#.00").format(diff) + "元</br></br>";
                    } else {
                        result += "</br>截至目前," + orgService.get(deptid).getObjname() + "累计费用已超支:" + (-1 * diff) + "元,超支比例:" + ((-1 * diff) / totalbudgetvalue) * 100 + "%</br></br>";
                    }
                }
            }

                response.getWriter().print(result);

            return;
        }
    }

    private String getPeriodStart(String date){
        String year=date.substring(0,4);
        String lastyear=(NumberUtil.getIntegerValue(year)-1)+"";
        String nextyear=(NumberUtil.getIntegerValue(year)+1)+"";
        if(date.compareTo(year+"-01-25")<=0) return lastyear+"-12-26";
        else if(date.compareTo(year+"-01-26")>=0&&date.compareTo(year+"-02-25")<=0) return year+"-01-26";
        else if(date.compareTo(year+"-02-26")>=0&&date.compareTo(year+"-03-25")<=0) return year+"-02-26";
        else if(date.compareTo(year+"-03-26")>=0&&date.compareTo(year+"-04-25")<=0) return year+"-03-26";
        else if(date.compareTo(year+"-04-26")>=0&&date.compareTo(year+"-05-25")<=0) return year+"-04-26";
        else if(date.compareTo(year+"-05-26")>=0&&date.compareTo(year+"-06-25")<=0) return year+"-05-26";
        else if(date.compareTo(year+"-06-26")>=0&&date.compareTo(year+"-07-25")<=0) return year+"-06-26";
        else if(date.compareTo(year+"-07-26")>=0&&date.compareTo(year+"-08-25")<=0) return year+"-07-26";
        else if(date.compareTo(year+"-08-26")>=0&&date.compareTo(year+"-09-25")<=0) return year+"-08-26";
        else if(date.compareTo(year+"-09-26")>=0&&date.compareTo(year+"-10-25")<=0) return year+"-09-26";
        else if(date.compareTo(year+"-10-26")>=0&&date.compareTo(year+"-11-25")<=0) return year+"-10-26";
        else if(date.compareTo(year+"-11-26")>=0&&date.compareTo(year+"-12-25")<=0) return year+"-11-26";
        else if(date.compareTo(year+"-12-26")>=0) return year+"-12-26";
        else return null;
    }

    private String getPeriodEnd(String date) {
        String year = date.substring(0, 4);
        String lastyear = (NumberUtil.getIntegerValue(year) - 1) + "";
        String nextyear = (NumberUtil.getIntegerValue(year) + 1) + "";
        if (date.compareTo(year + "-01-25") <= 0) return year + "-01-25";
        else if (date.compareTo(year + "-01-26") >= 0 && date.compareTo(year + "-02-25") <= 0) return year + "-02-25";
        else if (date.compareTo(year + "-02-26") >= 0 && date.compareTo(year + "-03-25") <= 0) return year + "-03-25";
        else if (date.compareTo(year + "-03-26") >= 0 && date.compareTo(year + "-04-25") <= 0) return year + "-04-25";
        else if (date.compareTo(year + "-04-26") >= 0 && date.compareTo(year + "-05-25") <= 0) return year + "-05-25";
        else if (date.compareTo(year + "-05-26") >= 0 && date.compareTo(year + "-06-25") <= 0) return year + "-06-25";
        else if (date.compareTo(year + "-06-26") >= 0 && date.compareTo(year + "-07-25") <= 0) return year + "-07-25";
        else if (date.compareTo(year + "-07-26") >= 0 && date.compareTo(year + "-08-25") <= 0) return year + "-08-25";
        else if (date.compareTo(year + "-08-26") >= 0 && date.compareTo(year + "-09-25") <= 0) return year + "-09-25";
        else if (date.compareTo(year + "-09-26") >= 0 && date.compareTo(year + "-10-25") <= 0) return year + "-10-25";
        else if (date.compareTo(year + "-10-26") >= 0 && date.compareTo(year + "-11-25") <= 0) return year + "-11-25";
        else if (date.compareTo(year + "-11-26") >= 0 && date.compareTo(year + "-12-25") <= 0) return year + "-12-25";
        else if (date.compareTo(year + "-12-26") >= 0) return nextyear + "-01-25";
        else return null;
    }
}
